<?php
class Controller_UserTests extends Controller_Base
{
	public function index()
	{
		if($this->request->isPost()){
			$email = (string)$this->request->getParam('email');
			$testId = (int)$this->request->getParam('testId');
			$model = new Model_UserTests();
			$isValid = $model->isValid($email, $testId);
			if(!$isValid){
				$this->view->errorMessage = 'you are not autorized to start this test';
				return;
			}else{
				$model->save($testId);
				$this->redirect(array('ctrl' => 'UserTests', 'act' => 'start'));
			}
		}
		
		
		$this->view->pageTitle = self::BASE_PAGE_TITLE.' --- User Test';
		$this->view->title = 'User Test';
		
		$model = new Model_DbTable_Tests();
		$this->view->tests = $model->fetchAll();
	}
	
	public function start()
	{
		$testId = HackerU_Session::getInstance()->testId;
		if(!$testId){
			return $this->redirect(array('ctrl' => 'UserTests', 'act' => 'index'));
		}
		
		$model = new Model_UserTests();
		$this->view->testDetails = $model->getTestDetails($testId);	
	}
	
	public function result()
	{
		if(!$this->request->isPost()){
			return $this->_forward(array('act' => 'start'));
		}
		
		$data = $this->request->getPost();
		$testId = $data['testId'];
		
		unset($data['testId']);
		$answerIds = array_values($data);
		
		if($answerIds){
			$model = new Model_UserTests();
			$this->view->grade = $model->getResult($testId, $answerIds);
		}else{
			$this->view->grade = 0;
		}
	}
}